﻿using System;

namespace UnitBox {
	public static class Create {

		#region public methods

		/// <summary>
		/// Creates a new instance of the specified class by calling the given creation function.
		/// If configured to intercept calls, it will return whatever instance was specified instead.
		/// This allows test fakes to be returned and thus units to be isolated from creations.
		/// </summary>
		/// <typeparam name="T">the type of class to instantiate</typeparam>
		/// <param name="creationFunction">the function used to instantiate the class</param>
		/// <returns></returns>
		public static T New<T>( Func<T> creationFunction ) {
			T returnedInstance;

			// invoke the real creation function if there are no pending instances to swap
			if( UnitBoxInterceptions.IsLockedDown || !SwapQueue.HasPendingInstancesToSwap<T>()) {
				T createdInstance = creationFunction.Invoke();
				returnedInstance = createdInstance;
			} else { // we know there are pending instances to swap. return the next swapped instance
				T swappedInstance = SwapQueue.GetNextPendingInstanceToSwap<T>();
				returnedInstance = swappedInstance;
			}

			return returnedInstance;
		}

		#endregion

	}
}
